import { setLoading } from "@/store";
import axios, {
  AxiosError,
  AxiosInstance,
  AxiosRequestConfig,
  AxiosResponse,
  RawAxiosRequestHeaders,
} from "axios";
import store from "@/store";
import { message } from "antd";
type TResponse<D> = {
  data: D;
  extra: any;
  message: string;
  status: number;
  success: boolean;
};

const http: AxiosInstance = axios.create({ baseURL: "" });
http.interceptors.request.use((config: AxiosRequestConfig) => {
  store.dispatch(setLoading(true));
  const { employee } = store.getState();
  if (employee) {
    (config.headers as RawAxiosRequestHeaders)[
      "Authorization"
    ] = `Bearer ${employee.token}`;
  }
  return config;
});

http.interceptors.response.use(
  (response: AxiosResponse<TResponse<any>>) => {
    store.dispatch(setLoading(false));
    if (response.config.responseType !== "blob" && response.data.status !== 0) {
      message.warning(response.data.message);
    }
    return response;
  },
  (err: AxiosError<TResponse<any>>) => {
    store.dispatch(setLoading(false));
    message.info(err.response?.data.message);
    return null;
  }
);
export async function get<D>(url: string, config?: AxiosRequestConfig) {
  return http.get<TResponse<D>>(url, config).then((res) => res?.data?.data);
}

export async function down(url: string, config?: AxiosRequestConfig) {
  return http.get(url, config).then((res) => res);
}

export async function post<D>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
) {
  return http
    .post<TResponse<D>>(url, data, config)
    .then((res) => res?.data?.data);
}

export async function put<D>(
  url: string,
  data?: any,
  config?: AxiosRequestConfig
) {
  return http
    .put<TResponse<D>>(url, data, config)
    .then((res) => res?.data?.data);
}

export async function del<D>(url: string, config?: AxiosRequestConfig) {
  return http.delete<TResponse<D>>(url, config).then((res) => res?.data?.data);
}
